package com.example.demo.poc.example;

import com.jayway.jsonpath.JsonPath;
import net.minidev.json.JSONArray;
import org.apache.commons.io.FileUtils;
import org.apache.commons.text.StringEscapeUtils;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class AviatorVoltageTest {
    public static void main(String[] args) {
        File f = new File("d:\\20191009.json");
        String t = null;
        try {
            t = FileUtils.readFileToString(f, "UTF8");
            t = StringEscapeUtils.unescapeJava(t);
        } catch (IOException e) {
            e.printStackTrace();
        }
//            System.out.println(t);
        Object o = JsonPath.parse(t).read("$[*].current.voltage");
        System.out.println(o.getClass());
        if( o instanceof JSONArray) {
            List<Object> d = JSONArrayToObjectArray((JSONArray) o);
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("AviatorScript");
            engine.put("d", d);
            try {
                System.out.println(engine.eval("avg(d)"));
            } catch (ScriptException e) {
                e.printStackTrace();
            }
        }
    }

    private static List<Object> JSONArrayToObjectArray(JSONArray array) {

        List<Object> oArray = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {

            Object o = array.get(i);
            if (o instanceof Double) {
                oArray.add((Double) o);
            } else if (o instanceof Long) {
                oArray.add((Long) o);
            } else if (o instanceof String) {
                oArray.add((String) o);
            } else if (o instanceof BigDecimal) {
                BigDecimal b = (BigDecimal) o;
                if (new BigDecimal(b.longValue()).compareTo(b) == 0) {
                    oArray.add(b.longValue());
                } else {
                    oArray.add(b.doubleValue());
                }
            }
        }
        return oArray;
    }
}
